package com.dataaccess.dataaccess.config.rocketmq;

import com.dataaccess.dataaccess.support.utils.MyLogger;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.remoting.common.RemotingHelper;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

@Component
public class UserProducerBackups {
    @Resource
    public MyLogger logger;
    /**
     * 生产者的组名
     */
    @Value("${suning.rocketmq.producerGroupBackups}")
    private String producerGroup;

    /**
     * NameServer 地址
     */
    @Value("${suning.rocketmq.namesrvaddr}")
    private String namesrvAddr;

    //@PostConstruct
    public void produder(String jsonstr) {
        DefaultMQProducer producer = new DefaultMQProducer(producerGroup);
        producer.setNamesrvAddr(namesrvAddr);
        //解决has been created before, specify another name please.
        producer.setInstanceName(RunTimeUtil.getRocketMqUniqeInstanceName());
        try {
            producer.start();
            logger.info("发送消息:" + "------" + jsonstr);
            Message message = new Message("user-topic", "user-tag", jsonstr.getBytes(RemotingHelper.DEFAULT_CHARSET));
            SendResult result = producer.send(message);
            logger.info("发送响应：MsgId:" + result.getMsgId() + "，发送状态:" + result.getSendStatus());
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            producer.shutdown();
        }
    }
}
